from decimal import Decimal

from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated
from django_redis import get_redis_connection
from goods.models import SKU
from .serializers import CartSKUSerializer, OrderSettlementSerializer,CreateOrderSerializer
from rest_framework.response import Response


class OrderSettlementView(APIView):
    """
    订单结算
    1. 需要登录的用户才可已可以提交订单
    2. 根据登录用户的信息，获取购物车的数据
    3. 购物车的数据在redis中
    4. 我们获取选中的商品的数据
    5.根据id获取商品的消息信息
    """
    permission_classes = [IsAuthenticated]

    def get(self, request):
        # 获取登录的用户
        user = request.user
        # 连接redis获取数据
        redis_conn = get_redis_connection('cart')
        redis_cart = redis_conn.hgetall('cart_%s' % user.id)
        redis_selected_ids = redis_conn.smembers('cart_selected_%s' % user.id)
        # 获取商品sku_id，强制转换类型
        cart = {}
        for sku_id in redis_selected_ids:
            cart[int(sku_id)] = int(redis_cart[sku_id])
        ids = cart.keys()
        # 获取所有商品
        skus = SKU.objects.filter(pk__in=ids)
        # 获取所有商品的数量
        for sku in skus:
            sku.count = cart[sku.id]
        # 添加运费信息
        freight = Decimal('10.0')
        serializer = OrderSettlementSerializer({'freight': freight, 'skus': skus})
        return Response(serializer.data)


class CreateOrderView(APIView):
    permission_classes = [IsAuthenticated]

    def post(self, request):
        serializer = CreateOrderSerializer(data=request.data,context={'request':request})
        serializer.is_valid()
        serializer.save()

        return Response(serializer.data)
